<template>
  <div>
    <template v-for="tag in tags">
      <a-tooltip v-if="tag.length > 20"
                 :key="tag"
                 :title="tag">
        <a-tag :key="tag"
               :closable="true"
               @close="() => handleClose(tag)">{{ `${tag.slice(0, 20)}...` }}</a-tag>
      </a-tooltip>
      <a-tag v-else
             :key="tag"
             :closable="true"
             @close="() => handleClose(tag)">{{ tag }}</a-tag>
    </template>
    <a-input v-if="inputVisible"
             ref="input"
             type="text"
             size="small"
             :style="{ width: '78px' }"
             :value="inputValue"
             @change="handleInputChange"
             @blur="handleInputConfirm"
             @keyup.enter="handleInputConfirm" />
    <a-tag v-else
           style="background: #fff; borderStyle: dashed;"
           @click="showInput">
      <a-icon type="plus" />{{label}}
    </a-tag>
  </div>
</template>
<script>
export default {
  data () {
    return {
      tags: [],
      inputVisible: false,
      inputValue: ''
    }
  },
  props: {
    mytags: {
      type: Array,
      default: () => []
    },
    label: {
      type: String,
      default: '添加标签'
    }
  },
  watch: {
    mytags: {
      handler (val, oldVal) {
        this.tags = val
      },
      deep: true,
      immediate: true
    }
  },
  methods: {
    // 关闭标签
    handleClose (removedTag) {
      const tags = this.tags.filter(tag => tag !== removedTag)
      this.$emit('changeTags', tags)
      this.tags = tags
    },
    // 显示输入框
    showInput () {
      this.inputVisible = true
      this.$nextTick(function () {
        this.$refs.input.focus()
      })
    },
    // 修改标签
    handleInputChange (e) {
      this.inputValue = e.target.value
    },
    // 添加标签
    handleInputConfirm () {
      const inputValue = this.inputValue
      let tags = this.tags
      if (inputValue && tags.indexOf(inputValue) === -1) {
        tags = [...tags, inputValue]
      }
      this.$emit('changeTags', tags)
      Object.assign(this, {
        tags,
        inputVisible: false,
        inputValue: ''
      })
    }
  }
}
</script>
